package com.liyong.pullorder.channels.parse;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liyong.pullorder.channels.dto.StandardOrderDto;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JsonParserStrategy implements ParserStrategy {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String getFormat() { return "JSON"; }

    @Override
    public List<StandardOrderDto> parse(String input, Map<String, String> fieldMapping) {
        List<StandardOrderDto> list = new ArrayList<>();
        try {
            JsonNode root = mapper.readTree(input);
            JsonNode items = root.isArray() ? root : root.path("items");
            Iterator<JsonNode> it = items.elements();
            while (it.hasNext()) {
                JsonNode node = it.next();
                StandardOrderDto dto = new StandardOrderDto();
                dto.setOrderId(text(node, fieldMapping.getOrDefault("orderId", "orderId")));
                dto.setStatus(text(node, fieldMapping.getOrDefault("status", "status")));
                dto.setAmount(decimal(node, fieldMapping.getOrDefault("amount", "amount")));
                dto.setCreatedAt(text(node, fieldMapping.getOrDefault("createdAt", "createdAt")));
                list.add(dto);
            }
        } catch (Exception e) {
            throw new RuntimeException("JSON parse error: " + e.getMessage(), e);
        }
        return list;
    }

    private String text(JsonNode node, String field) {
        return node.path(field).asText(null);
    }
    private java.math.BigDecimal decimal(JsonNode node, String field) {
        String txt = node.path(field).asText(null);
        return txt == null ? null : new java.math.BigDecimal(txt);
    }
}